package com.example.mygrade.intercepter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginIntercepter implements HandlerInterceptor {
    //  执行controller之前要执行的事情
    @Override
    public boolean preHandle(HttpServletRequest request,
                                       HttpServletResponse response,
                                       Object handler) throws Exception{
        //  首先捕获session，再看有没有用户的信息
        Object code = request.getSession().getAttribute(GlobalConstant.TEACHER_SESSION_ID.getMsg());
        Object code1 = request.getSession().getAttribute(GlobalConstant.USER_SESSION_ID.getMsg());
        Object code2 = request.getSession().getAttribute(GlobalConstant.MANAGE_SESSION_ID.getMsg());
        // 判断学生通的过或者管理员或者老师通得过，都要return true
        // ==null 判断是否登录
        log.info(request.getRequestURI().toString());
        if ((code == null || code.equals("")) && (code1 == null || code1.equals("")) && (code2 == null || code2.equals(""))){
            // response设置一个状态，如果没有权限应当有一个专门的状态码，403错误forbidden
            response.setStatus(HttpStatus.FORBIDDEN.value());

            // response.sendRedirect("/login/student")，只适合于后端服务器跳转
            log.info("请先登录"+request.getRequestURI());
            // 拦截器拦截下来
            return false;
        }
        return true;
    }
//    执行之后要执行的事情
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception{

    }
//    所有完成之后要执行的事情
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler,Exception ex) throws Exception{

    }
}
